//==============================相关图层参数====================

/*函数调用方法说明：
 *
 * 1.查询功能：
 *  方法：query(valuearr)
 *  参数：valuearr为经过云量、分辨率等初步筛选后所有符合条件的结合表ImageName值（影像名）组成的数组
 *  返回值：经空间查询后符合条件的ImageName值（影像名）组成的数组
 *  说明：调用该函数后将在给出的结合表范围内进行空间查询，并返回满足条件的影像名，同时淡黄色显示查到的结合表
 *  例子：quary(new Array('GF1_WFV2_E119.6_N27.6_20140508_L1A0000220216','GF1_PMS1_E120.1_N30.3_20130825_L1A0000074538-PAN1'))     
 *
 * 2.显示当前页面结合表区域（示例网站中的蓝色边框部分）
 *  方法：light(lightimgarr)
 *  参数：lightimgarr为当前页面结合表ImageName值组成的数组
 *  
 * 3.高亮鼠标所在条目的结合表（红色框）
 *  方法：鼠标移入触发：Highlight(imgname) //红色高亮显示
 *        鼠标移出触发：clearLight() //清除红色高亮
 *  参数：imgname为当前结合表的ImageName值（影像名）
 *  例子：//滑动高亮按钮
 *   var highlightBtn1=document.getElementById("highlightBtn1");
 *   highlightBtn1.onmouseover=function(e){
 *      Highlight('GF1_WFV2_E119.6_N27.6_20140508_L1A0000220216');
 *    }
 *    highlightBtn1.onmouseout=function(e){
 *      clearLight(); 
 *    }
 *
 * 4.显示当前结合表具体影像（示例网站中眼睛按钮）
 *  方法：displayImg(imgname)//显示  undisplayImg()//隐藏
 *  参数：imgname为当前结合表的ImageName值（影像名）
 *  例子：displayImg('GF1_PMS1_E120.1_N30.3_20130825_L1A0000074538-MSS1')
 *
 * 5.行政区边界查询正在测试中，loadBoundary(level,name)，其中level为1时查询市市级，2时查询县级，为0时清空（此时name随便填）
 *
 */
//工作空间地址：
var workSpaceUrl = "http://118.178.140.168:8080/geoserver/ZJRS"
//工作空间名称：
var workSpace = "ZJRS"
//坐标系：
var srsName = "EPSG:4326"
//天地图KEY:
var TiandituKey = "1d11420a769aa2d5763e1a67378995bb"
//影像底图图层（天地图）：
var baseImgLayer = "http://t0.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=" + TiandituKey
//市级行政区图层名：
var shijiLayer = "ZJRS:District"
//县级行政区图层名：
var xianjiLayer = "ZJRS:County2020"
//结合表图层名：
var targetLayer = "ZJRS:AllSingleScope"
//属性查询字段名（包括调用影像时匹配的字段名）：
var field = "ImageName"
//属性查询字段值（在该范围内匹配）：
//var valuearr=new Array('GF1_WFV2_E119.6_N27.6_20140508_L1A0000220216','GF1_PMS1_E120.1_N30.3_20130825_L1A0000074538-PAN1')
//当前页所有结合表字段值（名称）数组（淡黄色区域显示）：
var lightimgarr = new Array('GF1_WFV2_E119.6_N27.6_20140508_L1A0000220216',
	'GF1_PMS1_E120.1_N30.3_20130825_L1A0000074538-PAN1')

//平移系数
var panRate = 10; //单次平移时间(毫秒)
var panLength = 6; //单次平移距离系数

/*关于缩放：若地图自带缩放按钮无法使用，可新建相关按钮，
调用zoomMinus()及zoomPlus()即可缩小/放大，
参数不填默认为1（即缩/放1级）*/


//选中行政区边界样式(红色轮廓高亮)
var boundSource = new ol.source.Vector();
var boundVector = new ol.layer.Vector({
	source: boundSource,
	style: new ol.style.Style({
		stroke: new ol.style.Stroke({
			color: 'rgba(255, 0, 0, 1.0)',
			width: 5
		})
	}),
	zIndex: 994
});

//结果样式(黄色半透明显示)
var resultSource = new ol.source.Vector();
var resultVector = new ol.layer.Vector({
	title: "结合表",
	source: resultSource,
	style: new ol.style.Style({
		fill: new ol.style.Fill({
			color: 'rgba(254, 209, 16, 1.0)'
		})
	}),
	zIndex: 996
});

//高亮选中结合表结果样式
var spaceSource = new ol.source.Vector();
var spaceVector = new ol.layer.Vector({
	source: spaceSource,
	style: new ol.style.Style({
		stroke: new ol.style.Stroke({
			color: 'rgba(255, 0, 0, 1.0)',
			width: 3
		})
	}),
	zIndex: 999
});

//当前页结合表样式(蓝色边框显示)
var cpageSource = new ol.source.Vector();
var cpageVector = new ol.layer.Vector({
	source: cpageSource,
	style: new ol.style.Style({
		stroke: new ol.style.Stroke({
			color: 'rgba(0, 0, 255, 1.0)',
			width: 2
		})
	}),
	zIndex: 995
});

//图形绘制样式
var drawSource = new ol.source.Vector({
	wrapX: false
});
var drawVector = new ol.layer.Vector({
	source: drawSource,
	style: new ol.style.Style({
		fill: new ol.style.Fill({
			color: 'rgba(255, 255, 255, 0.2)'
		}),
		stroke: new ol.style.Stroke({
			color: '#ffcc33',
			width: 2
		}),
		image: new ol.style.Circle({
			radius: 7,
			fill: new ol.style.Fill({
				color: '#ffcc33'
			})
		})
	}),
	zIndex: 997
});

var extent = [118.02826723613758, 27.144488188499174, 122.82884918112711, 31.18275392885731];
//投影坐标系
var projection = new ol.proj.Projection({
	code: srsName,
	units: ol.proj.Units,
	extent: extent
});
//中心点
var center = ol.extent.getCenter(extent);

//实例化鼠标位置控件（MousePosition）
var mousePositionControl = new ol.control.MousePosition({
	//坐标格式
	coordinateFormat: ol.coordinate.createStringXY(6),
	//地图投影坐标系（若未设置则输出为默认投影坐标系下的坐标）
	//projection: 'EPSG:4326',
	//坐标信息显示样式类名，默认是'ol-mouse-position'
	className: 'custom-mouse-position',
	//显示鼠标位置信息的目标容器
	target: document.getElementById('mouse-position'),
	//未定义坐标的标记
	undefinedHTML: '&nbsp;'
});



function init() {
	//创建一个地图容器
	map = new ol.Map({
		target: 'map',
		view: new ol.View({
			center: center,
			zoom: 1,
			projection: projection,
			extent: extent,
			minZoom: 1
		}),
		interactions: new ol.interaction.defaults({
			doubleClickZoom: false
		}),
		controls: ol.control.defaults({ //地图中默认控件
			/* @type {ol.control.Attribution} */
			attributionOptions: ({
				//地图数据源信息控件是否可收缩,默认为true
				collapsible: true
			})
		}).extend([mousePositionControl]) //加载鼠标位置控件
	});

	/*======创建基于地图文档的WMS图层对象并加载到地图中======*/
	TiandiMap_img = new ol.layer.Tile({
		title: "天地图影像图",
		source: new ol.source.XYZ({
			url: baseImgLayer,
			wrapX: false
		})
	});
	//基于地图文档的WMS访问基地址
	wmsUrl = workSpaceUrl + "/wms";
	//创建基于地图文档的WMS图层对象
	wmsVectLayer0 = new ol.layer.Image({
		title: "市级行政区划图",
		source: new ol.source.ImageWMS({
			//WMS服务地址
			url: wmsUrl,
			//图层等参数，若WMS版本较老必须加上版本号
			params: {
				'LAYERS': shijiLayer,
				'VERSION': '1.1.1',
				'TILED': true
			},
			projection: projection,
			//服务类型
			serverType: 'geoserver'
		})

	});
	wmsVectLayer1 = new ol.layer.Image({
		title: "县级行政区划图",
		source: new ol.source.ImageWMS({
			//WMS服务地址
			url: wmsUrl,
			//图层等参数，若WMS版本较老必须加上版本号
			params: {
				'LAYERS': xianjiLayer,
				'VERSION': '1.1.1',
				'TILED': true
			},
			projection: projection,
			//服务类型
			serverType: 'geoserver'
		})

	});
	map.addLayer(TiandiMap_img);
	map.addLayer(wmsVectLayer0);
	map.addLayer(wmsVectLayer1);
}
init();
map.addLayer(drawVector);
map.addLayer(spaceVector);
map.addLayer(cpageVector);

//地图视图的初始参数
var view = map.getView();
//var zoom = view.getZoom();
//var center = view.getCenter();
//var rotation = view.getRotation();

//鹰眼底图
var wmsVectLayer3 = new ol.layer.Image({
	source: new ol.source.ImageWMS({
		//WMS服务地址
		url: wmsUrl,
		//图层等参数，若WMS版本较老必须加上版本号
		params: {
			'LAYERS': shijiLayer + ',' + xianjiLayer,
			'VERSION': '1.1.1',
			'TILED': true
		},
		projection: projection,
		//服务类型
		serverType: 'geoserver'
	})
});

//鹰眼地图控件
var extent1 = [112, 23, 128, 37]
var overviewMapControl = new ol.control.OverviewMap({
	//鹰眼控件样式（see in overviewmap-custom.html to see the custom CSS used）
	className: 'ol-overviewmap ol-custom-overviewmap',
	//鹰眼中加载同坐标系下不同数据源的图层
	layers: [wmsVectLayer3],
	//鹰眼控件展开时功能按钮上的标识（网页的JS的字符编码）
	collapseLabel: '\u00BB',
	//鹰眼控件折叠时功能按钮上的标识（网页的JS的字符编码）
	label: '\u00AB',
	//初始为展开显示方式
	collapsed: false,
	//maxResolution:this.map.maxResolution/4,
	view: new ol.View({
		center: center,
		zoom: 1,
		projection: new ol.proj.Projection({
			code: srsName,
			units: ol.proj.Units,
			extent: extent1
		}),
		extent: extent1
	}),
});
map.addControl(overviewMapControl);


// 添加图层切换控件
var layerSwitcher = new ol.control.LayerSwitcher({
	tipLabel: '切换图层'
});
map.addControl(layerSwitcher);

//显示全图
function reSetView() {
	//初始中心点
	view.setCenter(center);
	//初始旋转角度
	view.setRotation(0);
	//初始缩放级数
	view.setZoom(1);
}

function zoomMinus(val = 1) {
	//获取地图视图
	var view1 = map.getView();
	//获得当前缩放级数
	var zoom1 = view.getZoom();
	//地图缩小一级
	if (zoom1 > 1) {
		view1.setZoom(zoom1 - val);
	}
}

function zoomPlus(val = 1) {
	//获取地图视图
	var view2 = map.getView();
	//获得当前缩放级数
	var zoom2 = view.getZoom();
	//地图放大一级
	if (zoom2 < 28) {
		view1.setZoom(zoom2 + val);
	}
}


var feature;
var draw;
var typeSelect = document.getElementById('type');
var value;

function addInteraction() {
	if (drawSource == null) {
		drawSource = new ol.source.Vector({
			wrapX: false
		});
		//添加绘制层数据源
		drawVector.setSource(drawSource);
	}
	if (value === 'Polygon') {
		draw = new ol.interaction.Draw({
			source: drawSource,
			type: 'Polygon'
		});
	} else if (value === 'Box') {
		draw = new ol.interaction.Draw({
			source: drawSource,
			type: 'Circle',
			geometryFunction: ol.interaction.Draw.createBox()
		});
	} else if (value === 'Square') {
		draw = new ol.interaction.Draw({
			source: drawSource,
			type: 'Circle',
			geometryFunction: ol.interaction.Draw.createRegularPolygon(4)
		});
	} else if (value === 'LineString') {
		draw = new ol.interaction.Draw({
			source: drawSource,
			type: 'LineString'
		});
	} else if (value === 'Point') {
		draw = new ol.interaction.Draw({
			source: drawSource,
			type: 'Point'
		});
	} else {
		draw = new ol.interaction.Draw({
			source: drawSource,
			type: 'Polygon'
		});
	}
	map.addInteraction(draw);
	draw.on('drawend', function(evt) {
		feature = evt.feature;
		map.removeInteraction(draw);
		map.getView().fit(feature.getGeometry().getExtent());
		zoomMinus(0.5);
	})

}

//选择事件 
function DrawRec(val) {
	ClearDraw();
	if (val == 1) {
		value = "Polygon";
	} else {
		value = "Box";
	}
	map.removeInteraction(draw);
	addInteraction();
};


var hasBo = 0 //边界展示状态
function loadBoundary(level, name) {
	if (hasBo == 1) {
		boundSource = null;
		boundVector.setSource(boundSource);
		map.removeLayer(boundVector);
		hasBo = 0
	}
	if (level != 0) {
		if (level == 1) { //加载市级行政区边界
			var RequestBound = new ol.format.WFS().writeGetFeature({
				srsName: srsName,
				featureNS: workSpaceUrl,
				featurePrefix: workSpace,
				featureTypes: [shijiLayer],
				outputFormat: 'application/json',
				filter: ol.format.filter.equalTo('NAME', name),
			});
		} else { //加载县级行政区边界
			var RequestBound = new ol.format.WFS().writeGetFeature({
				srsName: srsName,
				featureNS: workSpaceUrl,
				featurePrefix: workSpace,
				featureTypes: [xianjiLayer],
				outputFormat: 'application/json',
				filter: ol.format.filter.equalTo('NAME', name),
			});
		}
		fetch(workSpaceUrl + '/wfs', {
			method: 'POST',
			body: new XMLSerializer().serializeToString(RequestBound)
		}).then(function(response) {
			return response.json();
		}).then(function(json) {
			var Boundary = new ol.format.GeoJSON().readFeatures(json);
			if (Boundary.length == 0) {
				alert('未找到相关行政区')
			} else {
				boundSource = new ol.source.Vector();
				boundSource.addFeatures(Boundary);
				boundVector.setSource(boundSource);
				map.getView().fit(boundSource.getExtent());
			}
		});
		map.addLayer(boundVector);
		hasBo = 1
	}
}




//查询
var q = 0 //判断是否查询过
function query(valuearr) {
	var valuestr = "%27" + valuearr.join("%27%2c%27") + "%27";
	if (feature !== null && feature !== undefined) {
		var fanwei = feature.getGeometry().getCoordinates();
		var fwstr = fanwei.toString();
		var t = ""; //定义t为格式化后的坐标字符串
		var num = 0;
		for (i = 0; i < fwstr.length; i++) {
			if (fwstr.charAt(i) !== ",") {
				t = t + fwstr.charAt(i)
			} else {
				num = num + 1;
				if (num % 2 !== 0) {
					t = t + " "
				} else {
					t = t + fwstr.charAt(i)
				}
			}
		}

		resultSource = null;
		resultVector.setSource(resultSource);

		var resultArray = ""
		resultArray = new Array()
		var cql_filter = field + ' IN (' + valuestr + ') AND INTERSECTS(the_geom, SRID=4326; POLYGON((' + t + ')))'
		fetch(workSpaceUrl + '/wfs?service=WFS&request=GetFeature&version=1.1.0&typename=' + targetLayer +
			'&outputFormat=json&' + '&cql_filter=' + cql_filter).then(function(response) {
			return response.json();
		}).then(function(json) {
			var features = new ol.format.GeoJSON().readFeatures(json);
			for (var i in features) {
				resultArray.push(features[i]["values_"][field])
			}
			if (features.length == 0) {
				alert('没有数据')
			} else {
				resultSource = new ol.source.Vector();
				resultSource.addFeatures(features);
				resultVector.setSource(resultSource);
				map.getView().fit(resultSource.getExtent());
			}
		});
		alert("查询结束");
		q = 1;
		resultVector.setOpacity(0.35);
		map.addLayer(resultVector);
	} else {
		alert("未选定任何查询区域")
	}
	if (true) return resultArray;
}


function ClearDraw() { //重置图层
	value = ""
	drawSource = null;
	//清空绘制图形
	drawVector.setSource(drawSource);
	map.removeInteraction(draw);
	if (feature !== null) {
		feature = null;
	}
	//清除查询结果
	if (spaceSource !== null) {
		spaceSource = null;
		spaceVector.setSource(spaceSource);
	}
	if (q == 1) { //如果查询过，就删除图层
		map.removeLayer(resultVector);
		q = 0
		resultArray = ""
	}
	if (hasBo == 1) { //如果加载过，就删除边界
		boundSource = null;
		boundVector.setSource(boundSource);
		map.removeLayer(boundVector);
		hasBo = 0
	}
	if (display == 1) { //如果正在显示，就删除图层
		map.removeLayer(displayImgLayer);
		display = 0
	}
	//清除高亮
	spaceSource = null;
	spaceVector.setSource(spaceSource);
	cpageSource = null;
	cpageVector.setSource(cpageSource);
}


//高亮选中结合表边框
function Highlight(imgname) {
	spaceSource = null;
	spaceVector.setSource(spaceSource);
	var featureRequest2 = new ol.format.WFS().writeGetFeature({
		srsName: srsName,
		featureNS: workSpaceUrl,
		featurePrefix: workSpace,
		featureTypes: [targetLayer],
		outputFormat: 'application/json',
		filter: ol.format.filter.equalTo(field, imgname),
	});

	fetch(workSpaceUrl + '/wfs', {
		method: 'POST',
		body: new XMLSerializer().serializeToString(featureRequest2)
	}).then(function(response) {
		return response.json();
	}).then(function(json) {
		var features = new ol.format.GeoJSON().readFeatures(json);
		if (features.length == 0) {
			alert('没有数据')
		} else {
			spaceSource = new ol.source.Vector();
			spaceSource.addFeatures(features);
			spaceVector.setSource(spaceSource);
			//map.getView().fit(spaceSource.getExtent());
		}
	});
}

//清除红色高亮框
function clearLight() {
	spaceSource = null;
	spaceVector.setSource(spaceSource);
}

//滑动高亮按钮
var highlightBtn1 = document.getElementById("highlightBtn1");
highlightBtn1.onmouseover = function(e) {
	Highlight('GF1_WFV2_E119.6_N27.6_20140508_L1A0000220216');
}
highlightBtn1.onmouseout = function(e) {
	clearLight(); //鼠标移出清除高亮
}



//点亮当前页结合表区域（蓝色边框）
function light(lightimgarr) {
	cpageSource = null;
	cpageVector.setSource(cpageSource);
	cpageSource = new ol.source.Vector();
	for (var i in lightimgarr) {
		lightRequest(lightimgarr[i]);
	}
}

function lightRequest(imgname) {
	var featureRequest1 = new ol.format.WFS().writeGetFeature({
		srsName: srsName,
		featureNS: workSpaceUrl,
		featurePrefix: workSpace,
		featureTypes: [targetLayer],
		outputFormat: 'application/json',
		filter: ol.format.filter.equalTo(field, imgname),
	});

	fetch(workSpaceUrl + '/wfs', {
		method: 'POST',
		body: new XMLSerializer().serializeToString(featureRequest1)
	}).then(function(response) {
		return response.json();
	}).then(function(json) {
		var features = new ol.format.GeoJSON().readFeatures(json);
		cpageSource.addFeatures(features);
		cpageVector.setSource(cpageSource);
	});

}


var upbtn = document.getElementById("lightBtn");
upbtn.onclick = function(e) {
	light(lightimgarr);
}

//显示单个具体影像
var display = 0 //影像展示状态
var displayImgLayer;

function displayImg(imgname) {
	undisplayImg();
	displayImgLayer = new ol.layer.Image({
		title: imgname,
		source: new ol.source.ImageWMS({
			//WMS服务地址
			url: wmsUrl,
			//图层等参数，若WMS版本较老必须加上版本号
			params: {
				'LAYERS': workSpace + ':' + imgname,
				'VERSION': '1.1.1',
				'FORMAT': "image/gif"
			},
			projection: projection,
			//服务类型
			serverType: 'geoserver'
		}),
		zIndex: 998
	});
	displayImgLayer.setOpacity(1000)
	map.addLayer(displayImgLayer);
	display = 1;
}

function undisplayImg() { //移除结合表影像
	if (display == 1) {
		map.removeLayer(displayImgLayer);
		display = 0
	}
}

//地图平移
function panDirection(direction) {
	var lonlat = 0.00000000001 * panLength; //平移系数
	var mapCenter = view.getCenter();
	switch (direction) {
		case 'north':
			mapCenter[1] += lonlat * Math.pow(2, 30 - view.getZoom());
			break;
		case "south":
			mapCenter[1] -= lonlat * Math.pow(2, 30 - view.getZoom());
			break;
		case "west":
			mapCenter[0] -= lonlat * Math.pow(2, 30 - view.getZoom());
			break;
		case "east":
			mapCenter[0] += lonlat * Math.pow(2, 30 - view.getZoom());
			break;
	}
	//更改center 实现地图平移
	view.animate({
		center: mapCenter,
	});
	//对地图进行渲染
	//map.render();
}

var tid;
var upbtn = document.getElementById("moveUp");
upbtn.onmousedown = function(e) {
	tid = setInterval(function() {
		panDirection("north");
	}, panRate);
}
upbtn.onmouseup = function(e) {
	clearInterval(tid);
}
upbtn.onmouseout = function(e) {
	clearInterval(tid);
}

var downbtn = document.getElementById("moveDown");
downbtn.onmousedown = function(e) {
	tid = setInterval(function() {
		panDirection("south");
	}, panRate);
}
downbtn.onmouseup = function(e) {
	clearInterval(tid);
}
downbtn.onmouseout = function(e) {
	clearInterval(tid);
}

var leftbtn = document.getElementById("moveLeft");
leftbtn.onmousedown = function(e) {
	tid = setInterval(function() {
		panDirection("west");
	}, panRate);
}
leftbtn.onmouseup = function(e) {
	clearInterval(tid);
}
leftbtn.onmouseout = function(e) {
	clearInterval(tid);
}

var rightbtn = document.getElementById("moveRight");
rightbtn.onmousedown = function(e) {
	tid = setInterval(function() {
		panDirection("east");
	}, panRate);
}
rightbtn.onmouseup = function(e) {
	clearInterval(tid);
}
rightbtn.onmouseout = function(e) {
	clearInterval(tid);
}
